﻿using A.M.ETO;
using A.M.Storage.Application;
using AutoMapper;
using DotNetCore.CAP;
using J.M.Inventory.Application.IInventoryServices;
using J.M.Inventory.Domain.DTO;
using J.M.Inventory.Domain.Entity;
using J.M.Inventory.Infrastruecure.IInventoryRepository;
using J.M.Inventory.Infrastruecure.InventoryRepository;
using Newtonsoft.Json;
using Public_Class_Library;
using Q.M.Sell.Doamin.DTO;
using Q.M.Sell.Doamin.Entity;
using Redis_ClientInfor;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace J.M.Inventory.Application.InventoryServices
{
    /// <summary>
    /// 入库管理表服务层实现
    /// </summary>
    public class Stock_managementServices : BaseServices<stock_management, string>, IStock_managementServices
    {
        //入库管理表
        private readonly IStock_managementRepository stock_managementRepository;
        private readonly IMapper mapper;
        //仓库表
        private readonly IWarehouseRepository warehouseRepository;
        //入库类型表
        private readonly IEnter_warehouseRepository enter_WarehouseRepository;
        ////跨服务
        private readonly Cross_service_Helper cross_Service_Helper;

        private readonly ICapPublisher capPublisher;
        public Stock_managementServices(IStock_managementRepository stock_managementRepository, IMapper mapper, IEnter_warehouseRepository enter_WarehouseRepository, IWarehouseRepository warehouseRepository, Cross_service_Helper cross_Service_Helper, ICapPublisher capPublisher) : base(stock_managementRepository)
        {
            this.enter_WarehouseRepository = enter_WarehouseRepository;
            this.mapper = mapper;
            this.stock_managementRepository = stock_managementRepository;
            this.warehouseRepository = warehouseRepository;
            this.cross_Service_Helper = cross_Service_Helper;
            this.capPublisher = capPublisher;
        }
        //入库显示+查询
        public PageETO<stock_managementDTO>  GetStockShow(string? code, int pageIndex, int pageSize)
        {
            PageETO<stock_managementDTO> pageETO = new PageETO<stock_managementDTO>();
            Expression<Func<stock_management, bool>> exception = i => true;
            if (!string.IsNullOrEmpty(code))
            {
                exception = x => x.entermange_id.Contains(code);
            }
            var list = from a in stock_managementRepository.GetShowQueryable(exception).ToList()
                       join b in enter_WarehouseRepository.GetShowQueryable().ToList() on a.enter_warehouseid equals b.nterwarehouse_id
                       join c in warehouseRepository.GetShowInfor().ToList() on a.entermange_enterwarehouseid equals c.warehousecode
                       select new stock_managementDTO
                       {
                           entermange_auditstate = a.entermange_auditstate,
                           entermange_datatime = a.entermange_datatime,
                           entermange_enterdepartmentid = a.entermange_enterdepartmentid,
                           entermange_enterwarehouseid = a.entermange_enterwarehouseid,
                           entermange_id = a.entermange_id,
                           entermange_Incomingsubject = a.entermange_Incomingsubject,
                           entermange_linkman = a.entermange_linkman,
                           entermange_phone = a.entermange_phone,
                           production_order = a.production_order,
                           entermange_project = a.entermange_project,
                           entermange_remark = a.entermange_remark,
                           entermange_upload = a.entermange_upload,
                           entermange_warehousingpersonnel = a.entermange_warehousingpersonnel,
                           enter_warehouseid = b.nterwarehouse_id,
                           nterwarehouse_name = b.nterwarehouse_name,
                           entermange_number = a.entermange_number,
                             warehousename = c.warehousename,

                       };
            pageETO.TotalCount = list.Count();
            pageETO.PageCount = (int)Math.Ceiling(pageETO.TotalCount / (double)pageSize);
            pageETO.Data = list.OrderByDescending(x => x.entermange_datatime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return pageETO;

        }
        /// <summary>
        /// 删除入库表
        /// </summary>
        /// <param name="stockid"></param>
        /// <returns></returns>
       public   int DeleteStock(string? stockid)
        {
             
             
            var list =  stock_managementRepository.GetShowObj(x => x.entermange_id == stockid);
            if (list == null)
            {
                return -1;
            }
            return stock_managementRepository.DelInfor(list);
        }
        /// <summary>
        /// 查询仓库表
        /// </summary>
        /// <returns></returns>
       public async Task<ApiReturn<warehouse>> GetShowQueryable()
        {
            ApiReturn<warehouse> apiReturn = new ApiReturn<warehouse>();
            var lsit=await warehouseRepository.GetShowQueryableAsync();
            apiReturn.Code = 200;
            apiReturn.ListInfor = lsit.Select(x => new warehouse
            {
                warehousecode=x.warehousecode,
                warehousename=x.warehousename,
            }).ToList();
            return apiReturn;
        }
        /// <summary>
        /// 新增入库
        /// </summary>
        /// <param name="stock_ManagementAddDTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
       public async Task<ApiReturn<string>> GetStockAddInfo(Stock_managementAddDTO stock_ManagementAddDTO)
        {

            ApiReturn<string> apiReturn = new ApiReturn<string>();
            var stock = mapper.Map<stock_management>(stock_ManagementAddDTO);
                var res1 = cross_Service_Helper.Get("http://10.31.59.5:5123/api/Approval_form/GetShowSystem").Result;
                var geinfor = JsonConvert.DeserializeObject<List<ShengPiDTO>>(res1);
                //判断审批状态是否开启
                var xiaos = geinfor.Where(c => c.approval_name == "库存系统").FirstOrDefault();
                if (xiaos.approval_on_no)
                {
                    //如果为开启状态存入Redis中
                    RedisClient.redisClient.HsetInforAsync("RukUinfor", stock_ManagementAddDTO.entermange_id, stock);
                    //添加成功需要传一个消息队列  传递哪个模块 还有编号
                    string numberName = "入库系统-" + stock_ManagementAddDTO.entermange_id;
                    capPublisher.Publish("GetNewNumber", numberName);
                    apiReturn.Code = 300;
                    apiReturn.Message = "等待审批，审批后自动执行";
                    return apiReturn;
                }
                else
                {
                    var res = await stock_managementRepository.AddInfor_Async(stock);
                    apiReturn.Code = 200;
                    apiReturn.Message = "添加成功";
                    //添加成功需要传一个消息队列  传递哪个模块 还有编号
                    string numberName = "入库系统-" + stock_ManagementAddDTO.entermange_id;
                    capPublisher.Publish("GetNewNumber", numberName);
                    stock_managementRepository.CommitTranInfor();
                }
            return apiReturn;
        }
        /// <summary>
        /// 普通添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiReturn<string>> GetAddXsInfor(string? id)
        {
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            var rew = await RedisClient.redisClient.HgetInforAsync<stock_management>("RukUinfor", id); 
            await stock_managementRepository.AddInfor_Async(rew); 
            apiReturn.Code = 200;
            apiReturn.Message = "添加成功";
            return apiReturn;

        }


        /// <summary>
        /// 修改入库信息
        /// </summary>
        /// <param name="Stock_managementAddDTO"></param>
        /// <returns></returns>
        public async Task<ApiReturn<string>> PostStockUpdateInfo(Stock_managementAddDTO Stock_managementAddDTO)
        {
            ApiReturn<string> apiReturn=new ApiReturn<string>();
            var stock= mapper.Map<stock_management>(Stock_managementAddDTO);
            var res = stock_managementRepository.GetShowInfor(x => x.entermange_id.Equals(Stock_managementAddDTO.entermange_id));
          
            var number = await stock_managementRepository.UpdInfor_Async(stock);
            if (number > 0)
            {
                apiReturn.Code = 200;
                apiReturn.Message = "修改成功";
            }
            else
            {
                apiReturn.Code = 400;
                apiReturn.Message = "修改失败";
            }
            return apiReturn;
        }
        /// <summary>
        /// 反填入库信息
        /// </summary>
        /// <param name="entermange_id"></param>
        /// <returns></returns>
       public async Task<stock_management> FindStockInfo(string? entermange_id)
        {
            Expression<Func<stock_management,bool>> i=x=>x.entermange_id== entermange_id;
            var res= await stock_managementRepository.GetShowObjAsync(i);
            return res;
             
        }

        //Task<ApiReturn<string>> IStock_managementServices.Deletestock(string? stockcode)
        //{
        //    throw new NotImplementedException();
        //}
    }
}
